package handler

import (
	"fmt"
	"gitee.com/sansaniot/ssiot-core/facade/env"
	jwt "gitee.com/sansaniot/ssiot-core/httpmvc/jwtauth"
	"github.com/gin-gonic/gin"
	"ssadmin/common/constant"
)

// IdentityHandler login后，普通请求携带token时，解析token中得payload
func IdentityHandler(c *gin.Context) interface{} {
	claims := jwt.ExtractClaims(c)
	userName := claims[constant.CacheKeyUserName]
	return userName
}

// Authorizator 从缓存中取出用户信息，并设置上下文，缓存在登陆时设置
func Authorizator(data interface{}, c *gin.Context) bool {
	if data == nil {
		return false
	}

	// 从缓存中取出用户信息，缓存在登陆时设置
	key := fmt.Sprintf("login_user:%s", data.(string))
	userId, err := env.Cache.HashGet(key, constant.CacheKeyUserId)
	deptIds, err := env.Cache.HashGet(key, constant.CacheKeyUserDeptIds)
	detName, err := env.Cache.HashGet(key, constant.CacheKeyUserDeptName)
	roleIds, err := env.Cache.HashGet(key, constant.CacheKeyUserRoleIds)
	agencyId, err := env.Cache.HashGet(key, constant.CacheKeyAgencyId)
	creatorId, err := env.Cache.HashGet(key, constant.CacheKeyCreatorId)
	creator, err := env.Cache.HashGet(key, constant.CacheKeyCreator)
	avator, err := env.Cache.HashGet(key, constant.CacheKeyAvatar)
	alias, err := env.Cache.HashGet(key, constant.CacheKeyCreator)

	if err != nil {
		return false
	}

	// 设置上下文
	userInfo := map[string]interface{}{
		constant.CacheKeyUserDeptIds:  deptIds,
		constant.CacheKeyUserDeptName: detName,
		constant.CacheKeyUserRoleIds:  roleIds,
		constant.CacheKeyAgencyId:     agencyId,
		constant.CacheKeyUserId:       userId,
		constant.CacheKeyUserName:     data,
		constant.CacheKeyCreator:      creator,
		constant.CacheKeyCreatorId:    creatorId,
		constant.CacheKeyAvatar:       avator,
		constant.CacheKeyAlias:        alias,
	}
	c.Set(constant.CacheKeyUserInfo, userInfo)
	return true
}
